package com.boarsoft.boar.common;

import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boarsoft.boar.CommonConfig;
import com.boarsoft.common.util.HttpClientUtil;

public class SMSUtil {
	private static Logger log = LoggerFactory.getLogger(SMSUtil.class);
	
	/**
	 * 发送即时短信，附带了平台签名
	 * 
	 * @param to
	 * @param key 资源字符串的KEY
	 * @param arguments 资源字符串中的参数
	 */
	public static boolean sendNow(String to, String key, Object... arguments) {
		ResourceBundle rb = ResourceBundle.getBundle("i18n/msg");
		String sms = rb.getString(key);
		sms = MessageFormat.format(sms, arguments);
		sms = sms.concat(rb.getString("sms.signature"));
		if (SMSUtil.send2(to, sms, "")) {
			log.info(String.format("Sent %s to %s.", sms, to));
			return true;
		}
		log.error(String.format("Send %s to %s failed.", sms, to));
		return false;
	}

	/**
	 * 发送短信
	 * 
	 * @param nums
	 *            目标号码，以逗号分隔
	 * @param text
	 *            内容
	 * @param time
	 *            计划发送时间，格式 2014-08-29 20:00:00
	 * @return
	 */
	private static boolean send2(String nums, String text, String time) {
		text = text.replaceAll("'", "");
		text = text.replaceAll("<br/>", " ");
		log.info(String.format("Send SMS %s %s : %s", nums, time, text));
		try {
			//text = URLEncoder.encode(text, "UTF-8");
			text = URLEncoder.encode(text, "GBK");
			String url = MessageFormat.format(CommonConfig.SMS_URL, nums, text, time);
			log.debug("SMS url is {}", url);
			String rs = HttpClientUtil.sendGet(url);
			if ("0\r\n".equals(rs)) {
				return true;
			}
			log.error("Error on send sms return : ".concat(rs));
		} catch (Exception e) {
			log.error("Error on send sms.", e);
		}
		return false;
	}
}
